home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 2 / AACD 2.iso / AACD / Programming / perlman / man / perllol.txt < prev    next >
Encoding:
Text File  |  1999-09-09  |  10.2 KB  |  329 lines

  1. NAME
  2.        perlLoL - Manipulating Lists of Lists in Perl
  3.  
  4. DESCRIPTION
  5. Declaration and Access of Lists of Lists
  6.        The simplest thing to build is a list of lists (sometimes
  7.        called an array of arrays).  It's reasonably easy to
  8.        understand, and almost everything that applies here will
  9.        also be applicable later on with the fancier data
  10.        structures.
  11.  
  12.        A list of lists, or an array of an array if you would, is
  13.        just a regular old array @LoL that you can get at with two
  14.        subscripts, like $LoL[3][2].  Here's a declaration of the
  15.        array:
  16.  
  17.            # assign to our array a list of list references
  18.            @LoL = (
  19.                   [ "fred", "barney" ],
  20.                   [ "george", "jane", "elroy" ],
  21.                   [ "homer", "marge", "bart" ],
  22.            );
  23.  
  24.            print $LoL[2][2];
  25.          bart
  26.  
  27.        Now you should be very careful that the outer bracket type
  28.        is a round one, that is, parentheses.  That's because
  29.        you're assigning to an @list, so you need parens.  If you
  30.        wanted there not to be an @LoL, but rather just a
  31.        reference to it, you could do something more like this:
  32.  
  33.            # assign a reference to list of list references
  34.            $ref_to_LoL = [
  35.                [ "fred", "barney", "pebbles", "bambam", "dino", ],
  36.                [ "homer", "bart", "marge", "maggie", ],
  37.                [ "george", "jane", "alroy", "judy", ],
  38.            ];
  39.  
  40.            print $ref_to_LoL->[2][2];
  41.  
  42.        Notice that the outer bracket type has changed, and so our
  43.        access syntax has also changed.  That's because unlike C,
  44.        in perl you can't freely interchange arrays and references
  45.        thereto.  $ref_to_LoL is a reference to an array, whereas
  46.        @LoL is an array proper.  Likewise, $LoL[2] is not an
  47.        array, but an array ref.  So how come you can write these:
  48.  
  49.            $LoL[2][2]
  50.            $ref_to_LoL->[2][2]
  51.  
  52.        instead of having to write these:
  53.  
  54.  
  55.            $LoL[2]->[2]
  56.            $ref_to_LoL->[2]->[2]
  57.  
  58.        Well, that's because the rule is that on adjacent brackets
  59.        only (whether square or curly), you are free to omit the
  60.        pointer dereferencing array.  But you need not do so for
  61.        the very first one if it's a scalar containing a
  62.        reference, which means that $ref_to_LoL always needs it.
  63.  
  64. Growing Your Own
  65.        That's all well and good for declaration of a fixed data
  66.        structure, but what if you wanted to add new elements on
  67.        the fly, or build it up entirely from scratch?
  68.  
  69.        First, let's look at reading it in from a file.  This is
  70.        something like adding a row at a time.  We'll assume that
  71.        there's a flat file in which each line is a row and each
  72.        word an element.  If you're trying to develop an @LoL list
  73.        containing all these, here's the right way to do that:
  74.  
  75.            while (<>) {
  76.                @tmp = split;
  77.                push @LoL, [ @tmp ];
  78.            }
  79.  
  80.        You might also have loaded that from a function:
  81.  
  82.            for $i ( 1 .. 10 ) {
  83.                $LoL[$i] = [ somefunc($i) ];
  84.            }
  85.  
  86.        Or you might have had a temporary variable sitting around
  87.        with the list in it.
  88.  
  89.            for $i ( 1 .. 10 ) {
  90.                @tmp = somefunc($i);
  91.                $LoL[$i] = [ @tmp ];
  92.            }
  93.  
  94.        It's very important that you make sure to use the [] list
  95.        reference constructor.  That's because this will be very
  96.        wrong:
  97.  
  98.            $LoL[$i] = @tmp;
  99.  
  100.        You see, assigning a named list like that to a scalar just
  101.        counts the number of elements in @tmp, which probably
  102.        isn't what you want.
  103.  
  104.        If you are running under use strict, you'll have to add
  105.        some declarations to make it happy:
  106.  
  107.  
  108.  
  109.            use strict;
  110.            my(@LoL, @tmp);
  111.            while (<>) {
  112.                @tmp = split;
  113.                push @LoL, [ @tmp ];
  114.            }
  115.  
  116.        Of course, you don't need the temporary array to have a
  117.        name at all:
  118.  
  119.            while (<>) {
  120.                push @LoL, [ split ];
  121.            }
  122.  
  123.        You also don't have to use push().  You could just make a
  124.        direct assignment if you knew where you wanted to put it:
  125.  
  126.            my (@LoL, $i, $line);
  127.            for $i ( 0 .. 10 )
  128.                $line = <>;
  129.                $LoL[$i] = [ split ' ', $line ];
  130.            }
  131.  
  132.        or even just
  133.  
  134.            my (@LoL, $i);
  135.            for $i ( 0 .. 10 )
  136.                $LoL[$i] = [ split ' ', <> ];
  137.            }
  138.  
  139.        You should in general be leary of using potential list
  140.        functions in a scalar context without explicitly stating
  141.        such.  This would be clearer to the casual reader:
  142.  
  143.            my (@LoL, $i);
  144.            for $i ( 0 .. 10 )
  145.                $LoL[$i] = [ split ' ', scalar(<>) ];
  146.            }
  147.  
  148.        If you wanted to have a $ref_to_LoL variable as a
  149.        reference to an array, you'd have to do something like
  150.        this:
  151.  
  152.            while (<>) {
  153.                push @$ref_to_LoL, [ split ];
  154.            }
  155.  
  156.        Actually, if you were using strict, you'd not only have to
  157.        declare $ref_to_LoL as you had to declare @LoL, but you'd
  158.        also having to initialize it to a reference to an empty
  159.        list.  (This was a bug in 5.001m that's been fixed for the
  160.        5.002 release.)
  161.  
  162.  
  163.            my $ref_to_LoL = [];
  164.            while (<>) {
  165.                push @$ref_to_LoL, [ split ];
  166.            }
  167.  
  168.        Ok, now you can add new rows.  What about adding new
  169.        columns?  If you're just dealing with matrices, it's often
  170.        easiest to use simple assignment:
  171.  
  172.            for $x (1 .. 10) {
  173.                for $y (1 .. 10) {
  174.                    $LoL[$x][$y] = func($x, $y);
  175.                }
  176.            }
  177.  
  178.            for $x ( 3, 7, 9 ) {
  179.                $LoL[$x][20] += func2($x);
  180.            }
  181.  
  182.        It doesn't matter whether those elements are already there
  183.        or not: it'll gladly create them for you, setting
  184.        intervening elements to undef as need be.
  185.  
  186.        If you just wanted to append to a row, you'd have to do
  187.        something a bit funnier looking:
  188.  
  189.            # add new columns to an existing row
  190.            push @{ $LoL[0] }, "wilma", "betty";
  191.  
  192.        Notice that I couldn't just say:
  193.  
  194.            push $LoL[0], "wilma", "betty";  # WRONG!
  195.  
  196.        In fact, that wouldn't even compile.  How come?  Because
  197.        the argument to push() must be a real array, not just a
  198.        reference to such.
  199.  
  200. Access and Printing
  201.        Now it's time to print your data structure out.  How are
  202.        you going to do that?  Well, if you only want one of the
  203.        elements, it's trivial:
  204.  
  205.            print $LoL[0][0];
  206.  
  207.        If you want to print the whole thing, though, you can't
  208.        just say
  209.  
  210.            print @LoL;         # WRONG
  211.  
  212.        because you'll just get references listed, and perl will
  213.        never automatically dereference things for you.  Instead,
  214.        you have to roll yourself a loop or two.  This prints the
  215.        whole structure, using the shell-style for() construct to
  216.        loop across the outer set of subscripts.
  217.            for $aref ( @LoL ) {
  218.                print "\t [ @$aref ],\n";
  219.            }
  220.  
  221.        If you wanted to keep track of subscripts, you might do
  222.        this:
  223.  
  224.            for $i ( 0 .. $#LoL ) {
  225.                print "\t elt $i is [ @{$LoL[$i]} ],\n";
  226.            }
  227.  
  228.        or maybe even this.  Notice the inner loop.
  229.  
  230.            for $i ( 0 .. $#LoL ) {
  231.                for $j ( 0 .. $#{$LoL[$i]} ) {
  232.                    print "elt $i $j is $LoL[$i][$j]\n";
  233.                }
  234.            }
  235.  
  236.        As you can see, it's getting a bit complicated.  That's
  237.        why sometimes is easier to take a temporary on your way
  238.        through:
  239.  
  240.            for $i ( 0 .. $#LoL ) {
  241.                $aref = $LoL[$i];
  242.                for $j ( 0 .. $#{$aref} ) {
  243.                    print "elt $i $j is $LoL[$i][$j]\n";
  244.                }
  245.            }
  246.  
  247.        Hm... that's still a bit ugly.  How about this:
  248.  
  249.            for $i ( 0 .. $#LoL ) {
  250.                $aref = $LoL[$i];
  251.                $n = @$aref - 1;
  252.                for $j ( 0 .. $n ) {
  253.                    print "elt $i $j is $LoL[$i][$j]\n";
  254.                }
  255.            }
  256.  
  257.  
  258. Slices
  259.        If you want to get at a slide (part of a row) in a
  260.        multidimensional array, you're going to have to do some
  261.        fancy subscripting.  That's because while we have a nice
  262.        synonym for single elements via the pointer arrow for
  263.        dereferencing, no such convenience exists for slices.
  264.        (Remember, of course, that you can always write a loop to
  265.        do a slice operation.)
  266.  
  267.        Here's how to do one operation using a loop.  We'll assume
  268.        an @LoL variable as before.
  269.  
  270.  
  271.            @part = ();
  272.            $x = 4;
  273.            for ($y = 7; $y < 13; $y++) {
  274.                push @part, $LoL[$x][$y];
  275.            }
  276.  
  277.        That same loop could be replaced with a slice operation:
  278.  
  279.            @part = @{ $LoL[4] } [ 7..12 ];
  280.  
  281.        but as you might well imagine, this is pretty rough on the
  282.        reader.
  283.  
  284.        Ah, but what if you wanted a two-dimensional slice, such
  285.        as having $x run from 4..8 and $y run from 7 to 12?  Hm...
  286.        here's the simple way:
  287.  
  288.            @newLoL = ();
  289.            for ($startx = $x = 4; $x <= 8; $x++) {
  290.                for ($starty = $y = 7; $x <= 12; $y++) {
  291.                    $newLoL[$x - $startx][$y - $starty] = $LoL[$x][$y];
  292.                }
  293.            }
  294.  
  295.        We can reduce some of the looping through slices
  296.  
  297.            for ($x = 4; $x <= 8; $x++) {
  298.                push @newLoL, [ @{ $LoL[$x] } [ 7..12 ] ];
  299.            }
  300.  
  301.        If you were into Schwartzian Transforms, you would
  302.        probably have selected map for that
  303.  
  304.            @newLoL = map { [ @{ $LoL[$_] } [ 7..12 ] ] } 4 .. 8;
  305.  
  306.        Although if your manager accused of seeking job security
  307.        (or rapid insecurity) through inscrutable code, it would
  308.        be hard to argue. :-) If I were you, I'd put that in a
  309.        function:
  310.  
  311.            @newLoL = splice_2D( \@LoL, 4 => 8, 7 => 12 );
  312.            sub splice_2D {
  313.                my $lrr = shift;        # ref to list of list refs!
  314.                my ($x_lo, $x_hi,
  315.                    $y_lo, $y_hi) = @_;
  316.  
  317.                return map {
  318.                    [ @{ $lrr->[$_] } [ $y_lo .. $y_hi ] ]
  319.                } $x_lo .. $x_hi;
  320.            }
  321.  
  322.  
  323. SEE ALSO
  324.        perldata(1), perlref(1), perldsc(1)
  325. AUTHOR
  326.        Tom Christiansen <tchrist@perl.com>
  327.  
  328.        Last udpate: Sat Oct  7 19:35:26 MDT 1995
  329.